import asyncio
import logging
import os
from ipykernel.kernelbase import Kernel
from .pty_interface import PTY
from .client import CPGQLSClient

pty_instance = PTY()
# pty_instance.write_command("docker run -it -v $(pwd):/workdir -p 8081:8081 registry.cn-wulanchabu.aliyuncs.com/sky-group/joern:20250418 joern --server --server-host 0.0.0.0 --server-port 8081")
logging.basicConfig(level=logging.DEBUG, filename="kernel.log")
logger = logging.getLogger(__name__)

server_endpoint = ("localhost:8081")
# basic_auth_credentials = ("username", "password")
client = CPGQLSClient(server_endpoint, auth_credentials=None, event_loop=None)

class EchoKernel(Kernel):
    implementation = 'Echo'
    implementation_version = '1.0'
    language = 'scala'
    language_version = '2.13'
    language_info = {
        'name': 'Scala',
        'mimetype': 'text/plain',
        'file_extension': '.sc',
    }
    banner = "Echo kernel - as useful as a parrot"

    def do_execute(self, code, silent, store_history=True, user_expressions=None,
                   allow_stdin=False):
        print(code, silent)
        # pty_instance.write_command(code)
        # code = pty_instance.read_output()
        # import re

        # ansi_escape = re.compile(r'\x1B$$[0-9;]*[a-zA-Z]')
        # cleaned_text = ansi_escape.sub('', code)
        logger.info(code)
        result = client.execute(code, )
# print(result)
        if result['success']:
            output = result['stdout'] 
        else:
            output = str(result)
        logger.info(result)
        if not silent:
            stream_content = {'name': 'stdout', 'text': output}
            self.send_response(self.iopub_socket, 'stream', stream_content)

        return {'status': 'ok',
                # The base class increments the execution count
                'execution_count': self.execution_count,
                'payload': [],
                'user_expressions': {},
               }

if __name__ == '__main__':
    from ipykernel.kernelapp import IPKernelApp
    IPKernelApp.launch_instance(kernel_class=EchoKernel)